<template>
  <div class="login_body">
    <van-tabs animated line-width="50%" line-height="0.01rem" :swipeable="true" color="#E74E4B">
      <!-- 登录方式1 -->
      <van-tab title="邮箱帐号登录" class="right_border">
        <van-form validate-first @submit="Codesubmit" ref="LoginForm">
          <van-field
            clearable
            v-model="user_input.email"
            name="email"
            placeholder="请输入邮箱"
            :rules="[{pattern:rule.email,message:'请输入正确的邮箱地址',trigger:'onBlur'}]"
          />
          <van-field
            v-model="user_input.yzm"
            clearable
            name="yam"
            placeholder="请输入验证码"
            type="number"
            :rules="[{validator:passwordRule,message:'请输入正确的验证码',trigger:'onBlur'}]">
            <template #button>
              <van-button 
                native-type="button"
                :loading="yam_btn_loading"
                loading-text="请稍后..."
                :disabled="is_disabled"
                @click="getyzm">{{send_eamil}}</van-button>
            </template>
            </van-field>
          <div style="margin: 0.16rem;">
            <van-button 
              round 
              block 
              :loading="code_login_loading"
              :disabled="code_login_disabled"
              native-type="submit"
              loading-text="登陆中 请稍后...">
              登 录
            </van-button>
          </div>
        </van-form>
      </van-tab>
      <!-- 登录方式2 -->
      <van-tab title="账号密码登录">
        <van-form validate-first @submit="login_by_password">
          <van-field
            v-model="user_input.email"
            name="username"
            clearable
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="user_input.password"
            clearable
            type="password"
            name="userpassword"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <div style="margin: 0.16rem;">
            <van-button round block type="info" native-type="submit">
              登 录 
            </van-button>
          </div>
        </van-form>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script>
export default {
  name:"LoginBody",
  data() {
    return {
      // 校验正则
      rule:{
        email:/^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/,
      },
      // 验证码的 loading 状态
      yam_btn_loading:false,
      is_disabled:false, // 是否禁用 发送邮件按钮
      send_eamil:"发送验证码",// 发送邮件 按钮 文字
      code_login_loading:false, // 验证码 登录 的loding 状态
      code_login_disabled:false,// 验证码 登陆 的 禁用状态
      // 用户登录 数据
      user_input:{
        email:"2084049306@qq.com",
        password:"",
        yzm:""
      }
    }
  },
  methods: {
    // 校验密码
    passwordRule(val){
      // 长度不能为0
      if(val.length == 0) return false;
      return true;
    },
    // 获取验证码
    async getyzm(){
      let isresult = true;// 记录校验是否通过
      const result = await this.$refs.LoginForm.validate("email").catch(err => {
        // 邮箱校验失败
        isresult = false;
      })
      if(!isresult) return this.$message({position:"center",message:"邮箱校验失败"});
      // 到此 邮箱校验成功
      // 发送 获取验证码请求
      this.yam_btn_loading = true;
      const {data:res} = await this.$http.post('/sendEmail',{email:this.user_input.email}).catch(err => {
        // 网络错误
        this.$message({position:"center",message:"请求超时 服务器未响应"});
        this.yam_btn_loading = false;
        return;
      });
      this.yam_btn_loading = false;
      if(!res.isok) return this.$message({position:"center",message:res.message});
      this.$message({position:"center",message:res.message});
      // 验证码倒计时
      this.CountDown();
    },
    // 倒计时
    CountDown(){
      this.is_disabled = true;// 禁用 按钮
      let sec = 60;
      // 启用倒计时
      let dao_timer = setInterval(() => {
        sec--;
        this.send_eamil = `发送验证码 (${sec}s)`;
        if(sec <= 0){
          clearInterval(dao_timer);
          this.is_disabled = false;
          this.send_eamil = `发送验证码`;
        }
      }, 1000);
    },
    // 提交表单 登录方式：验证码
    async Codesubmit(val){
      this.code_login_loading = true;
      this.code_login_disabled = true;
      // 发起 验证请求
      const {data:res} = await this.$http.post("/login",{type:"code",email:val.email,yzm:val.yam}).catch(err => {
        // 网络错误
        this.$message({position:"center",message:"请求超时 服务器未响应"});
        this.code_login_loading = false;
        this.code_login_disabled = false;
      });
      console.log(res);
      this.code_login_loading = false;
      this.code_login_disabled = false;
      this.$message({position:"center",message:res.message})
      if(!res.isok) return; // 错误
      // 登录成功
      // 存储token 跳转页面
      window.localStorage.setItem("token",res.data.token);
      this.$router.push("/home");
    },
    // 提交表单 登录方式:密码
    async login_by_password(val){
      const {data:res} = await this.$http.post("/login",{type:'password',email:this.user_input.email,password:this.user_input.password});
      this.$message({position:"center",message:res.message});
      if(!res.isok) return;
      // 存储token
      window.localStorage.setItem("token",res.data.token);
      // 跳转上一页
      // console.log(window.history.length);
      if(window.history.length <= 3){
        this.$router.push("/home");
      }else{
        this.$router.back();
      }
    }
  },
}
</script>
<style lang="less" scoped>
  .login_body{
    border-top: 0.01rem solid #F6F6F6;
    background-color: #ffffff;
  }
  .van-field{
    margin-top: 0.2rem;
  }
  .van-button{
    background-color: #E74E4B;
    color: #ffffff;
    border: none;
  }
</style>